using System;
using System.Text;
using System.IO;

// .NET 4.0: in System.Runtime.Serialization.dll 
// .NET 3.5: in System.ServiceModel.Web.dll
using System.Runtime.Serialization.Json;


namespace SharpObjects.EventBus
{

    internal class JsonSerialization
    {
        public static string Serialize(object obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            MemoryStream memoryStream = new MemoryStream();
            serializer.WriteObject(memoryStream, obj);
            string serialized = Encoding.Default.GetString(memoryStream.ToArray());
            return serialized;
        }

        public static object Deserialize<T>(string json, params Type[] knownTypes)
        {
            T obj;
            MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), knownTypes);
            obj = (T)serializer.ReadObject(memoryStream);
            memoryStream.Close();
            return obj;
        }

        public static T[] DeserializeToArray<T>(string json, params Type[] knownTypes)
        {
            T[] objs;
            MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T[]), knownTypes);
            objs = (T[])serializer.ReadObject(memoryStream);
            memoryStream.Close();
            return objs;
        }

    }
}